import json
import requests
from apps.sales_man.models import ApplicantList, VisitApplicant


class YouCardApi(object):
    def __init__(self):
        # self.key = "30339_Dv0xtyXaoM7ObnTfqNGRjO"
        self.key = "51607_7GukAe37Skl9OrhQsfDQ132Kt"

    def apply_card(self, product_id, username, phone, id_card):
        """
        申请信用卡
        :param product_id:
        :param username:
        :param phone:
        :param id_card:
        :return:
        """
        url = "https://www.youdancard.com/api/apply-card?key=%s" % self.key
        content = {
            "product_id": product_id,
            "username": username,
            "phone": phone,
            "id_card": id_card,
            "key": self.key
        }
        response = requests.post(url, data=content)
        result = response.content
        result = str(result, encoding='utf-8')
        content = json.loads(result)
        return content

    def visit_process(self, visit_id):
        """
        查询信用卡接口
        :param visit_id: 申请时 一个手机号和一个产品id返回的visit_id
        :return:
        """
        url = "https://www.youdancard.com/api/visit-process?visit_id=%s" % visit_id
        response = requests.get(url)
        result = response.content
        result = str(result, encoding='utf-8')
        content = json.loads(result)
        return content

    def visit_list(self):
        """
        我的办卡订单查询接口(不计算残件)
        :return:
        """
        url = "https://www.youdancard.com/api/visit-list?key=%s" % self.key
        response = requests.get(url, verify=False)
        result = response.content
        result = str(result, encoding='utf-8')
        content = json.loads(result)
        return content


def apply(product_obj, apply_obj):
    product_id = product_obj.productapiproduct.api_product  # 思兮 api id
    username = apply_obj.name
    phone = apply_obj.tel
    id_card = apply_obj.card
    card_api = YouCardApi()
    content = card_api.apply_card(product_id, username, phone, id_card)
    if content.get("code") != 0:
        return False, content
    else:
        visit_id = content.get("visit_id")
        VisitApplicant.objects.get_or_create(
            visit_id=visit_id,
            product=product_obj,
            applicant=apply_obj
        )
        return True, content
